package com.example.robertluozizhao.framecollectdemo.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.robertluozizhao.framecollectdemo.R;
import com.example.robertluozizhao.framecollectdemo.data.bean.AddressInfo;
import com.example.robertluozizhao.framecollectdemo.data.bean.CameraInfoHttp;
import com.example.robertluozizhao.framecollectdemo.data.bean.TreeBean;
import com.google.gson.Gson;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by robert.luozizhao on 2018/1/31.
 */

public class GgTestActivity extends AppCompatActivity {

    @BindView(R.id.tv_nor_str)
    TextView tvNorStr;
    @BindView(R.id.tv_final_str)
    TextView tvFinalStr;
    @BindView(R.id.tv_normal_int)
    EditText tvNormalInt;
    @BindView(R.id.tv_final_int)
    TextView tvFinalInt;
    @BindView(R.id.btn_change)
    Button btnChange;
    @BindView(R.id.ll_group)
    LinearLayout llGroup;
    private String testString = "123";
    private final static String fstestStr = "123";
    private int inttest = 123;
    private final static int fsinttest = 123;
    private String TAG = "GgTestActivity";

    private String treeJson = "{\"resultCode\":200,\"message\":\"SUCCESS\",\"data\":" +
            "[{\"id\":3,\"name\":\"第一级分组1\",\"children\":[{\"id\":1,\"name\":\"第二级分组1\"," +
            "\"children\":[{\"id\":4,\"name\":\"第三级分组1\",\"children\":[]},{\"id\":5," +
            "\"name\":\"第三级分组2\",\"children\":[{\"id\":79,\"name\":\"分组SAkc63PS\"," +
            "\"children\":[]}]},{\"id\":6,\"name\":\"第三级分组3\",\"children\":[]},{\"id\":7," +
            "\"name\":\"第三级分组4\",\"children\":[]},{\"id\":8,\"name\":\"第三级分组5\"," +
            "\"children\":[]},{\"id\":9,\"name\":\"第三级分组6\",\"children\":[]},{\"id\":10," +
            "\"name\":\"第三级分组7\",\"children\":[]},{\"id\":11,\"name\":\"第三级分组8\"," +
            "\"children\":[]}]},{\"id\":12,\"name\":\"第二级分组2\",\"children\":[{\"id\":13,\"" +
            "name\":\"第三级分组9\",\"children\":[]},{\"id\":14,\"name\":\"第三级分组10\",\"children\"" +
            ":[]},{\"id\":15,\"name\":\"第三级分组11\",\"children\":[]},{\"id\":16,\"name\":\"第三级分组12\"" +
            ",\"children\":[]},{\"id\":17,\"name\":\"第三级分组13\",\"children\":[]}]}]}]}";

    private String organizeJson = "[{\"organizationId\":\"d60a74ff-876d-5166-f335-287bfc1b8391\"," +
            "\"parentOrganizationId\":\"05616bd9-d9f9-4661-a7b1-d70d5ab71598\"," +
            "\"no\":\"2\"," +
            "\"organizationName\":\"二楼org\",\"organizationFullName\":\"zzj.二楼\"}," +
            "{\"organizationId\":\"53413c75-4cdb-3f91-b711-1ebcb5f772f2\"," +
            "\"parentOrganizationId\":\"05616bd9-d9f9-4661-a7b1-d70d5ab71598\"," +
            "\"no\":\"4\"," +
            "\"organizationName\":\"四楼org\",\"organizationFullName\":\"zzj.四楼\"}," +
            "{\"organizationId\":\"098ddc04-7c80-1b05-6e17-1076f9d42e78\"," +
            "\"parentOrganizationId\":\"05616bd9-d9f9-4661-a7b1-d70d5ab71598\"," +
            "\"no\":\"3\"," +
            "\"organizationName\":\"三楼org\",\"organizationFullName\":\"zzj.三楼\"}," +
            "{\"organizationId\":\"555555555555555555555555555555555555\"," +
            "\"no\":\"5\"," +
            "\"parentOrganizationId\":\"098ddc04-7c80-1b05-6e17-1076f9d42e78\"," +
            "\"organizationName\":\"三楼-1层org\",\"organizationFullName\":\"lzz层\"}," +
            "{\"organizationId\":\"666666666666666666666666666666666666\"," +
            "\"parentOrganizationId\":\"555555555555555555555555555555555555\"," +
            "\"no\":\"7\"," +
            "\"organizationName\":\"三楼-1层-室org\",\"organizationFullName\":\"lzz层\"}," +
            "{\"organizationId\":\"777777777777777777777777777777777777\"," +
            "\"parentOrganizationId\":\"666666666666666666666666666666666666\"," +
            "\"no\":\"9\"," +
            "\"organizationName\":\"三楼-1层-室-001org\",\"organizationFullName\":\"lzz层\"}," +
            "{\"organizationId\":\"106cb58c-b44a-5c62-f0c3-6d0fb3ff2a1e\"," +
            "\"parentOrganizationId\":\"777777777777777777777777777777777777\"," +
            "\"no\":\"5\"," +
            "\"parentOrganizationId\":\"05616bd9-d9f9-4661-a7b1-d70d5ab71598\"," +
            "\"organizationName\":\"6产品部NVRorg\",\"organizationFullName\":\"zzj.产品部NVR\"}]";

    private String organizeList1 = "[{\"cameraID\":\"82c57c11-b821-4aa6-e821-2cabe68d7607\"," +
            "\"cameraName\":\"lyq-1_camera\"," +
            "\"parentOrganizationId\":\"555555555555555555555555555555555555\"," +
            "\"cameraType\":\"枪机\"," +
            "\"cameraStatus\":\"\",\"organizationId\":\"58855\"" +
            ",\"encoderIP\":\"\",\"encoderChannelNum\":1,\"encoderUserName\":\"admin\",\"encoderPassword\":\"admin\",\"encoderPort\":9999,\"encoderTypeCode\":120000,\"forwardSvrIP\":\"58.62.220.138\",\"forwardSvrPort\":554,\"dcpSvrIP\":\"192.168.18.107\",\"dcpSvrPort\":9000,\"storageSvrIP\":null,\"storageSvrPort\":0,\"storageSvrUserName\":null,\"storageSvrPassword\":null,\"rtsp0\":\"rtsp://58.62.220.138:554/H264?admin&admin&120000&c8a6d4ea:0&1&0\",\"rtsp1\":\"rtsp://58.62.220.138:554/H264?admin&admin&120000&c8a6d4ea:0&1&1\",\"seriesNo\":\"c8a6d4ea\"}]";

    private String organizeList2 = "[{\"cameraID\":\"6cbf17cf-8e34-0482-5688-d807f61ff437\"," +
            "\"cameraName\":\"二楼-04_camera\"," +
            "\"parentOrganizationId\":\"666666666666666666666666666666666666\"," +
            "\"cameraType\":\"球机\",\"cameraStatus\":\"\",\"organizationId\":\"sfdfsfsf\",\"encoderIP\":\"\",\"encoderChannelNum\":4,\"encoderUserName\":\"admin\",\"encoderPassword\":\"admin123\",\"encoderPort\":8000,\"encoderTypeCode\":100204,\"forwardSvrIP\":\"58.62.220.138\",\"forwardSvrPort\":554,\"dcpSvrIP\":\"192.168.18.107\",\"dcpSvrPort\":9000,\"storageSvrIP\":null,\"storageSvrPort\":0,\"storageSvrUserName\":null,\"storageSvrPassword\":null,\"rtsp0\":\"rtsp://58.62.220.138:554/H264?admin123&admin&100204&C84499712:0&4&0\",\"rtsp1\":\"rtsp://58.62.220.138:554/H264?admin123&admin&100204&C84499712:0&4&1\",\"seriesNo\":\"C84499712\"}]";

    private String organizeList3 = "[{\"cameraID\":\"6cbf17cf-8e34-0482-5688-d807f61ff437\"," +
            "\"cameraName\":\"lzz层-01_camera\"," +
            "\"parentOrganizationId\":\"777777777777777777777777777777777777\"," +
            "\"cameraType\":\"球机\",\"cameraStatus\":\"\",\"organizationId\":\"fsfdse\",\"encoderIP\":\"\",\"encoderChannelNum\":4,\"encoderUserName\":\"admin\",\"encoderPassword\":\"admin123\",\"encoderPort\":8000,\"encoderTypeCode\":100204,\"forwardSvrIP\":\"58.62.220.138\",\"forwardSvrPort\":554,\"dcpSvrIP\":\"192.168.18.107\",\"dcpSvrPort\":9000,\"storageSvrIP\":null,\"storageSvrPort\":0,\"storageSvrUserName\":null,\"storageSvrPassword\":null,\"rtsp0\":\"rtsp://58.62.220.138:554/H264?admin123&admin&100204&C84499712:0&4&0\",\"rtsp1\":\"rtsp://58.62.220.138:554/H264?admin123&admin&100204&C84499712:0&4&1\",\"seriesNo\":\"C84499712\"}]";

//    private Map<String, AddressInfo> addressInfoMap;
    private List<CameraInfoHttp> cameraInfoHttpsList;
    private ArrayList<AddressInfo> addressInfos;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gg_test);
        ButterKnife.bind(this);
        tvNormalInt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d(TAG, "afterTextChanged: " + s.toString());
                inttest = Integer.parseInt(s.toString());
            }
        });


        Gson gson = new Gson();
//        TestTreeBean testTreeBean = gson.fromJson(treeJson, TestTreeBean.class);
//        List<TreeBean> data = testTreeBean.getData();
//        if (data != null && data.size() > 0) {
//            TreeNode root = TreeNode.root();
//            for (TreeBean treeBean : data) {
//                traverseTreeNode(treeBean, root);
//            }
//            AndroidTreeView tView = new AndroidTreeView(this, root);
//            tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom, true);
//            llGroup.addView(tView.getView());
//        }

        try {
            addressInfos = parseJson2List(organizeJson, AddressInfo.class);

            Comparator<AddressInfo> comp = new Comparator<AddressInfo>() {
                @Override
                public int compare(AddressInfo a1, AddressInfo a2) {
                    return a1.getNo() - a2.getNo();
                }
            };

            Collections.sort(addressInfos, comp);


            ArrayList<CameraInfoHttp> cameraInfoHttps1 = parseJson2List(organizeList1, CameraInfoHttp.class);
            ArrayList<CameraInfoHttp> cameraInfoHttps2 = parseJson2List(organizeList2, CameraInfoHttp.class);
            ArrayList<CameraInfoHttp> cameraInfoHttps3 = parseJson2List(organizeList3, CameraInfoHttp.class);
            cameraInfoHttpsList = new ArrayList<>();
            cameraInfoHttpsList.addAll(cameraInfoHttps1);
            cameraInfoHttpsList.addAll(cameraInfoHttps2);
            cameraInfoHttpsList.addAll(cameraInfoHttps3);


            TreeNode root = TreeNode.root();
            canvasView("05616bd9-d9f9-4661-a7b1-d70d5ab71598",root);
            AndroidTreeView tView = new AndroidTreeView(this, root);
            tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom, true);
            llGroup.addView(tView.getView());


        } catch (JSONException e) {
            e.printStackTrace();
        }


//        TreeNode child0 = new TreeNode(new IconTreeItem(1, "1-111111111111")).setViewHolder(new MyHolder(this));
//
//        TreeNode child0_1 = new TreeNode(new IconTreeItem(1, "1-1-1111111111")).setViewHolder(new MyHolder(this));
//        TreeNode child0_2 = new TreeNode(new IconTreeItem(1, "1-1-2111111111", true)).setViewHolder(new MyHolder(this));
//        child0.addChildren(child0_1, child0_2);
//
//
//        TreeNode child1 = new TreeNode(new IconTreeItem(2, "1-222222222222")).setViewHolder(new MyHolder(this));
//        TreeNode parent = new TreeNode(new IconTreeItem(2, "11111111111111")).setViewHolder(new MyHolder(this));
//        parent.addChildren(child0, child1);
//
//
//        TreeNode child3 = new TreeNode(new IconTreeItem(1, "2-111111111111", true)).setViewHolder(new MyHolder(this));
//        TreeNode child4 = new TreeNode(new IconTreeItem(2, "2-222222222222")).setViewHolder(new MyHolder(this));
//        TreeNode parent1 = new TreeNode(new IconTreeItem(2, "22222222222222")).setViewHolder(new MyHolder(this));
//        parent1.addChildren(child3, child4);
//
//
//        TreeNode root = TreeNode.root();
//        root.addChild(parent);
//        root.addChild(parent1);
//        AndroidTreeView tView = new AndroidTreeView(this, root);
//        tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom, true);
//        llGroup.addView(tView.getView());

    }

    private void canvasView(String orgid,TreeNode root) {
//        String org = "05616bd9-d9f9-4661-a7b1-d70d5ab71598";
        for (AddressInfo entry : addressInfos) {
            if (orgid.equals(entry.getParentOrganizationId())) {
                //绘制节点
                TreeNode treeNode = new TreeNode(new IconTreeItem(1, entry.getOrganizationName())).setViewHolder(new MyHolder(this));
                root.addChildren(treeNode);

                //绘制子节点
                if (cameraInfoHttpsList!=null) {
                    if (cameraInfoHttpsList.size()>0) {
                        for (int i = 0; i < cameraInfoHttpsList.size(); i++) {
                            if (cameraInfoHttpsList.get(i).getParentOrganizationId().equals(orgid)) {
                                root.addChildren(new TreeNode(new IconTreeItem(1, cameraInfoHttpsList.get(i).getCameraName())).setViewHolder(new MyHolder(this)));
                            }
                        }
                    }
                }

                canvasView(entry.getOrganizationId(),treeNode);
            }
        }

    }


    private void traverseTreeNode(TreeBean treeBean, TreeNode treeNode) {
        if (treeBean != null && treeBean.getChildren().size() > 0) {
            for (TreeBean bean : treeBean.getChildren()) {
                TreeNode tr = new TreeNode(new IconTreeItem(bean.getId(), bean.getName())).setViewHolder(new MyHolder(this));
                treeNode.addChildren(tr);
                traverseTreeNode(bean, tr);
            }
        } else {
            if (treeBean != null) {
                TreeNode tr = new TreeNode(new IconTreeItem(treeBean.getId(), treeBean.getName())).setViewHolder(new MyHolder(this));
                treeNode.addChildren(tr);
            }
        }
    }


    @OnClick(R.id.btn_change)
    public void onViewClicked() {
        tvNorStr.setText(testString);
        tvFinalStr.setText(fstestStr);
        tvNormalInt.setText(inttest + "");
        tvFinalInt.setText(fsinttest + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public class MyHolder extends TreeNode.BaseNodeViewHolder<IconTreeItem> {

        private ImageView mImageView;

        public MyHolder(Context context) {
            super(context);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public View createNodeView(TreeNode node, IconTreeItem value) {
            final LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(R.layout.layout_profile_node, null, false);
            TextView tvValue = (TextView) view.findViewById(R.id.node_value);
            mImageView = (ImageView) view.findViewById(R.id.iv_indication);

            List<TreeNode> children = node.getChildren();
            if (children == null || children.size() == 0) {
                mImageView.setVisibility(View.GONE);
            } else {
                mImageView.setImageResource(R.drawable.list_icon);
            }

            tvValue.setText(value.text);

            node.setClickListener(new TreeNode.TreeNodeClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onClick(TreeNode node, Object value) {
                    List<TreeNode> children = node.getChildren();
                    if (children != null || children.size() > 0) {
                        if (node.isExpanded()) {
                            mImageView.setImageResource(R.drawable.list_icon);
                        } else {
                            mImageView.setImageResource(R.drawable.ic_down);
                        }
                    }
                    Toast.makeText(GgTestActivity.this, "node:" + node + ",value:" + value, Toast.LENGTH_SHORT).show();
                }
            });
            return view;
        }

//        @Override
//        public void toggle(boolean active) {
//            mImageView.setImageResource(active ? R.drawable.ic_down : R.drawable.list_icon);
//        }
    }

    public class IconTreeItem {
        public int icon;
        public String text;
        private boolean isQj;

        public IconTreeItem(int icon, String text) {
            this.icon = icon;
            this.text = text;
        }

        public IconTreeItem(int icon, String text, boolean isQj) {
            this.icon = icon;
            this.text = text;
            this.isQj = isQj;
        }

        public int getIcon() {
            return icon;
        }

        public void setIcon(int icon) {
            this.icon = icon;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public boolean isQj() {
            return isQj;
        }

        public void setQj(boolean qj) {
            isQj = qj;
        }
    }

    /**
     * 将json字串转换成集合对象
     *
     * @param jsonData json字符
     * @param c        需转换成的java对象
     * @param <T>      java对象类型
     * @return 返回转换后的java类型集合
     * @throws JSONException 抛出json解析异常
     * @author christinRuan
     * @date 2016/7/1  9:07
     * @returnType ArrayList<T>
     */
    public static <T> ArrayList<T> parseJson2List(String jsonData, Class<T> c)
            throws JSONException {

        if (null == jsonData || "".equals(jsonData))
            return null;

        Gson gson = new Gson();
        ArrayList<T> list = new ArrayList<T>();
        JSONArray jsonArray = new JSONArray(jsonData.trim());
        JSONObject objItem = null;
        T objT = null;
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            objItem = (JSONObject) jsonArray.get(i);
            if (null != objItem) {
                objT = gson.fromJson(objItem.toString(), c);
                list.add(objT);
            }
        }


        return list;
    }
}
